package com.lazydong.apiforward.client.gui.util;

import cn.hutool.core.util.StrUtil;
import com.lazydong.apiforward.client.global.GlobalData;
import com.lazydong.apiforward.client.gui.pages.appmain.Environment;
import com.lazydong.apiforward.gateway.component.GatewayDynamicRoute;
import com.lazydong.apiforward.gateway.component.GatewayDynamicRouteComponent;
import com.lazydong.apiforward.gateway.model.RouteDefinitionInfo;

public class RouteUpdateUtil implements GatewayDynamicRoute {

    private static GatewayDynamicRouteComponent component;

    public static void updateEnvironmentRoute() {
        if (!GlobalData.ROUTE_SERVER_STATUS.get()) {
            return;
        }
        Environment environment = GlobalData.GLOBAL_ENVIRONMENT.get();
        if (environment == null) {
            RouteDefinitionInfo routeDefinitionInfo = new RouteDefinitionInfo();
            routeDefinitionInfo.setServiceId("environment");
            routeDefinitionInfo.setPredicate("/**");
            routeDefinitionInfo.setUrl(null);
            RouteUpdateUtil.component.routeChangeEvent(routeDefinitionInfo);
            return;
        }
        String proxyEnvDomain = GlobalData.getProxyEnvDomain();
        if (StrUtil.equals(proxyEnvDomain, GlobalData.CURRENT_ENVIRONMENT_DOMAIN_STR.get())) {
            System.out.println("当前兜底环境没有变化，无需改动");
            return;
        }
        GlobalData.CURRENT_ENVIRONMENT_DOMAIN_STR.set(proxyEnvDomain);
        RouteDefinitionInfo routeDefinitionInfo = new RouteDefinitionInfo();
        routeDefinitionInfo.setServiceId("environment");
        routeDefinitionInfo.setPredicate("/**");
        routeDefinitionInfo.setUrl(proxyEnvDomain);
        routeDefinitionInfo.setOrdered(Integer.MAX_VALUE);
        RouteUpdateUtil.component.routeChangeEvent(routeDefinitionInfo);
    }

    /**
     * 更新路由
     *
     * @param id        唯一id
     * @param predicate 断言
     * @param address   转发后的路由
     */
    public static void updateRoute(String id, String predicate, String address) {
        if (!GlobalData.ROUTE_SERVER_STATUS.get()) {
            return;
        }
        RouteDefinitionInfo routeDefinitionInfo = new RouteDefinitionInfo();
        routeDefinitionInfo.setServiceId(id);
        routeDefinitionInfo.setPredicate(predicate);
        routeDefinitionInfo.setUrl(address);
        RouteUpdateUtil.component.routeChangeEvent(routeDefinitionInfo);
    }

    @Override
    public void setDynamicRouteComponent(GatewayDynamicRouteComponent gatewayDynamicRouteComponent) {
        RouteUpdateUtil.component = gatewayDynamicRouteComponent;
    }
}
